<template>
  <!-- 民警管理 -- 新增/编辑 -->
  <div>
    <public-modal
      width="600px"
      :footer="false"
      :title="title"
      :publicVisible="publicVisible"
      @handleOk="handleOk"
      @cancel="cancel"
    >
      <div slot="content" :style="{ height: status === 0 ? '300px' : 'auto' }">
        <a-form-model
          ref="form"
          :model="form"
          :rules="rules"
          class="formStyle"
          autocomplete="off"
          layout="inline"
          :labelCol="{ style: 'width: 100px' }"
        >
          <a-row :gutter="24">
            <a-col :span="7" class="imageUpload">
              <a-row :gutter="24">
                <a-col :span="24">
                  <a-form-item>
                    <a-upload
                      :remove="remove"
                      :file-list="fileList"
                      @change="uploadChange"
                      class="avatar-uploader"
                      list-type="picture-card"
                      :customRequest="customRequest"
                      :showUploadList="showUploadList"
                      accept="image/png, image/JPG,image/jpeg"
                    >
                      <div v-if="fileList.length < 1">
                        <img class="pictIcon" src="@/assets/imgs/pict-icon.png" alt="" />
                        <p class="imgText">点击上传</p>
                      </div>
                    </a-upload>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-col>
            <a-col :span="17">
              <a-form-model-item label="人员姓名" prop="userName">
                <a-input :maxLength="30" autocomplete="off" placeholder="请输入人员姓名" v-model="form.userName" />
              </a-form-model-item>

              <a-form-model-item label="手机号码" prop="mobile">
                <a-input :maxLength="30" autocomplete="off" placeholder="请输入手机号码" v-model="form.mobile" />
              </a-form-model-item>

              <a-form-model-item label="民警警号" v-if="status == 0">
                <a-input :maxLength="30" autocomplete="off" placeholder="请输入民警警号" v-model="form.policeUserNo" />
              </a-form-model-item>

              <a-form-model-item label="身份证号">
                <a-input :maxLength="30" autocomplete="off" placeholder="请输入身份证号" v-model="form.idCard" />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </public-modal>
  </div>
</template>

<script>
import { uploadFile } from '@/api/api'
import { checkIDCard } from '@/utils/validate.js'
import publicModal from '@/components/publicModal'
import { putAction, postAction } from '@/api/manage'
import { isMobile } from '../../../utils/validate'

export default {
  name: 'addPoliceModal',
  components: { publicModal },
  data() {
    return {
      title: '新增',
      record: {},
      status: 0,
      publicVisible: false,
      imageUrl: [],
      fileList: [],
      showUploadList: { showPreviewIcon: false },
      form: {},
      rules: {
        userName: [{ required: true, message: '请输入人员姓名!' }],
        mobile: [
          { required: true, message: '请输入手机号码!' },
          {
            validator: (rule, value, callback) => {
              if (!isMobile(value)) {
                callback(new Error('请输入正确的手机号码！'))
              } else {
                callback()
              }
            },
          },
        ],
      },
      enmu: ['民警', '辅警', '网格员'],
    }
  },
  mounted() {},
  methods: {
    async show(record, status = 0) {
      this.status = status
      this.record = record
      this.publicVisible = true

      if (record && record.id) {
        this.title = `编辑${this.enmu[status]}`
        this.form = { ...record }

        if (record.userImage) {
          const obj = {
            uid: record.userImage,
            name: record.userImage,
            status: 'done',
            url: record.imgPrefix + record.userImage,
          }
          this.fileList.push(obj)
          this.imageUrl.push(record.userImage)
        }
      } else {
        this.title = `新增${this.enmu[status]}`
      }
    },

    remove(file) {
      let uid = file.uid
      let index = this.fileList.findIndex((v) => {
        return v.uid == uid
      })

      this.fileList.splice(index, 1)
      this.imageUrl.splice(index, 1)
    },
    async customRequest(info) {
      let file = info.file
      const formData = new FormData()
      formData.append('file', file)
      if (this.status == 0) formData.append('type', 2)
      else if (this.status == 1) formData.append('type', 63)
      else if (this.status == 2) formData.append('type', 64)
      let res = await uploadFile(formData)
      if (res.code == 200) {
        this.imageUrl.push(res.result.halfPath)
      }
    },
    uploadChange({ file, fileList }) {
      file.status = 'done'
      this.fileList = fileList
    },

    handleOk() {
      this.$refs.form.validate(async (valid) => {
        if (!valid) return

        if (this.form.idCard && !checkIDCard(this.form.idCard)) {
          this.$message.error('请输入正确的身份证号!')
          return
        }

        if (this.imageUrl.length > 0) {
          this.form.userImage = this.imageUrl[0]
        }

        const apiPaths = {
          0: {
            add: '/police/user/add',
            edit: '/police/user/edit',
          },
          1: {
            add: '/police/auxiliary_user/add',
            edit: '/police/auxiliary_user/edit',
          },
          2: {
            add: '/police/grid_user/add',
            edit: '/police/grid_user/edit',
          },
        }

        const { add, edit } = apiPaths[this.status]
        const url = this.record.id ? edit : add
        const method = this.record.id ? putAction : postAction
        if (!this.record.id) this.form.policeAgencyId = this.record.policeAgencyId
        try {
          const res = await method(url, this.form)
          this.$message.success(res.message)
          this.$emit('refresh')
          this.cancel()
        } catch (error) {
          // 处理错误
          console.error('请求失败:', error)
          this.$message.error('请求失败，请稍后重试！')
        }
      })
    },

    cancel() {
      this.publicVisible = false
      this.fileList = []
      this.imageUrl = []
      this.form = {}
    },
  },
}
</script>

<style scoped lang="less">
.formStyle {
  padding: 0.2rem;
}

.imageUpload {
  margin-bottom: 150px;
  /deep/.avatar-uploader {
    > .ant-upload {
      width: 150px;
      height: 176px;
      background: var(--theme-input-bg);
      border: 1px solid var(--theme-input-border);
    }
  }

  /deep/.ant-upload-select-picture-card {
    width: 150px;
    height: 176px;
  }

  /deep/ .ant-upload-list-item {
    width: 150px;
    height: 176px;
  }

  .imgText {
    color: #1163b8;
    font-weight: 500;
  }

  .pictIcon {
    margin-bottom: 10px;
    width: 42px;
    height: 38px;
  }
}
</style>
